package com.test.demo.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.test.demo.model.DemoFileInfo;
import com.test.demo.service.DemoInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


@Controller
public class DemoInfoController {

    @Autowired
    private DemoInfoService demoInfoService;


    @GetMapping("/index")
    public String index() {
        return "test";
    }

    @ResponseBody
    @PostMapping("calculateH")
    public double calculateH(@RequestBody List<Map<String, Object>> infoList) {

        return 0.01d;
    }

    @ResponseBody
    @PostMapping("calculateHFile")
    public Map<String, Object> calculateHFile(@RequestParam MultipartFile file) throws IOException {

        return demoInfoService.calculateHFile(file);
    }


    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>1. 创建excel对应的实体对象 参照{@link  DemoFileInfo}
     * <p>2. 设置返回的 参数
     * <p>3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcelFactory.write(response.getOutputStream(), DemoFileInfo.class).sheet("模板").doWrite(null);
    }

    /**
     * 下载油品信息模板
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("downloadOilInfo")
    public void downloadOilInfo(HttpServletResponse response) throws IOException {
        demoInfoService.exportOilInfo(response, "油品信息模板");
    }


    /**
     * 上传容积表
     *
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("uploadVolume")
    public Boolean uploadVolume(@RequestParam MultipartFile file) {

        return demoInfoService.uploadVolume(file);
    }


}
